package com.uzai.console.service.jd.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.SysMsgTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.jd.jdtoken.*;
import com.uzai.console.entity.JdToken;
import com.uzai.console.entity.Merchant;
import com.uzai.console.mapper.JdTokenMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.jd.JdTokenService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.vo.jd.jdtoken.JdTokenInfoVo;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/***
 * 运营商基本配置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class JdTokenServiceImpl implements JdTokenService {


    Logger logger = LoggerFactory.getLogger(JdTokenServiceImpl.class);

    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    /**
     * 查询京东联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenQuery
     * @return null
     */
    public Page<JdTokenInfoVo> findJdTokenList(JdTokenQuery jdTokenQuery){
        //新建返回到页面的LIST对象
        List<JdTokenInfoVo> jdTokenInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<JdToken> page = new Page<>();
        jdTokenQuery.convert(page);
        ArrayList<JdToken> jdOrderList =  jdTokenMapper.findByList(page, jdTokenQuery);
        if(jdOrderList != null && jdOrderList.size() > 0){
            for (JdToken jdToken : jdOrderList){
                JdTokenInfoVo jdTokenInfoVo = new JdTokenInfoVo();
                BeanUtils.copyProperties(jdToken, jdTokenInfoVo);
                jdTokenInfoVoList.add(jdTokenInfoVo);
            }
        }

        //返回到页面分页对象
        Page<JdTokenInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(jdTokenInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询京东联盟详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenIdDto
     * @return null
     */
    public JdTokenInfoVo findJdTokenInfo(JdTokenIdDto jdTokenIdDto){

        if(jdTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        JdToken jdToken = jdTokenMapper.selectById(jdTokenIdDto.getId(), jdTokenIdDto.getMerId());
        if(jdToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该京东联盟账号不存在");
        }

        //返回页面对象
        JdTokenInfoVo jdTokenInfoVo = new JdTokenInfoVo();
        //将查询到的对象复制给返回页面对象
        BeanUtils.copyProperties(jdToken, jdTokenInfoVo);

        return jdTokenInfoVo;
    }

    /**
     * 添加京东联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenInfoDto
     * @return null
     */
    public void addJdToken(JdTokenInfoDto jdTokenInfoDto){

        JdToken jdToken = new JdToken();

        BeanUtils.copyProperties(jdTokenInfoDto, jdToken);

//        if(jdTokenInfoDto.getType() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择类型");
//        }

        if(jdTokenInfoDto.getType() == 0){ //添加京东
            if(StringUtils.isBlank(jdTokenInfoDto.getUnionId())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "京东联盟id不能为空");
            }
            jdToken.setAuthKey(jdTokenInfoDto.getUnionId());
        }else{
            if(StringUtils.isBlank(jdTokenInfoDto.getAuthKey())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "渠道编号不能为空");
            }
            jdToken.setUnionId(jdToken.getAuthKey());
        }

        JdToken jdToken_old = jdTokenMapper.selectByUnionId(jdTokenInfoDto.getUnionId());
        if(jdToken_old != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "联盟id已经存在");
        }

        jdToken.setId(IdWorker.getId());
        Integer now = DateUtil.getNowTime();
        jdToken.setCreateTime(now);
        jdToken.setUpdateTime(now);
        jdToken.setType(0); //京东
        jdTokenMapper.insertSelective(jdToken);

        //发送其他异常提醒
        Merchant merchant = merchantMapper.selectById(jdTokenInfoDto.getMerId());
        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(merchant.getId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue()); //其他异常提醒
        //消息
        JSONObject ext = new JSONObject();
        StringBuilder content = new StringBuilder();
        content.append("京东已增加联盟授权，账号").append(jdToken.getUnionId());
        //当前操作员
        ext.put("content", content.toString());
        ext.put("phone", merchant.getMobile());
        ext.put("errorcode", content.toString());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---京东添加联盟授权，发送其他异常消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));
        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
    }

    /**
     * 修改京东联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenInfoDto
     * @return null
     */
    public void updateJdToken(JdTokenInfoDto jdTokenInfoDto){

        if(jdTokenInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        JdToken jdToken = jdTokenMapper.selectById(jdTokenInfoDto.getId(), jdTokenInfoDto.getMerId());

        if(jdToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "联盟不存在");
        }

        Integer now = DateUtil.getNowTime();
        jdToken.setRemark(jdTokenInfoDto.getRemark());
        jdToken.setDefPid(jdTokenInfoDto.getDefPid());
        jdToken.setQueryRatio(jdTokenInfoDto.getQueryRatio());
        jdToken.setUpdateTime(now);
        jdTokenMapper.updateByIdSelective(jdToken);
    }

    /**
     * 添加京拥联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenInfoDto
     * @return null
     */
    public void addJyToken(JdTokenInfoDto jdTokenInfoDto){

        if(StringUtils.isBlank(jdTokenInfoDto.getAuthKey())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "渠道编号不能为空");
        }
//
//        if(jdTokenInfoDto.getType() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择类型");
//        }

        JdToken jdToken = new JdToken();
        BeanUtils.copyProperties(jdTokenInfoDto,jdToken);
        jdToken.setId(IdWorker.getId());
        jdToken.setType(1);
        Integer now = DateUtil.getNowTime();
        jdToken.setCreateTime(now);
        jdToken.setUpdateTime(now);

        jdTokenMapper.insertSelective(jdToken);
    }


    /**
     * 修改京拥联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenInfoDto
     * @return null
     */
    public void updateJyToken(JdTokenInfoDto jdTokenInfoDto){

        if(jdTokenInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        if(StringUtils.isBlank(jdTokenInfoDto.getUnionId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主体名称不能为空");
        }


        JdToken jdToken = jdTokenMapper.selectById(jdTokenInfoDto.getId(), jdTokenInfoDto.getMerId());

        jdToken.setUnionId(jdTokenInfoDto.getUnionId());
        Integer now = DateUtil.getNowTime();
        jdToken.setUpdateTime(now);
        jdTokenMapper.updateByIdSelective(jdToken);
    }

    /**
     * 删除联盟
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenIdDto
     * @return null
     */
    public void deleteToken(JdTokenIdDto jdTokenIdDto){
        if(jdTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }
        jdTokenMapper.deleteById(jdTokenIdDto.getId(), jdTokenIdDto.getMerId());

    }

//    /**
//     * 创建推广位
//     * @author liuqi
//     * @date 2021/8/13 11:38
//     * @param jdTokenCretePidDto
//     * @return null
//     */
//    public JdTokenCreatePidVo createPid(JdTokenCretePidDto jdTokenCretePidDto){
//
//        if(jdTokenCretePidDto.getId() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
//        }
//
//        if (jdTokenCretePidDto.getPidCount() == null || jdTokenCretePidDto.getPidCount() < 1 ){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
//        }
//        if (jdTokenCretePidDto.getPidCount()>50){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "一次最多50个推广位");
//        }
//
//        JdToken jt = jdTokenMapper.selectById(jdTokenCretePidDto.getId(), jdTokenCretePidDto.getMerId());
//        if (jt==null){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该联盟不存在");
//        }
//
//        JdTokenCreatePidVo jdTokenCreatePidVo = null;
//        List<String> pids = new ArrayList<>();
//        try {
//            JdClient client= new DefaultJdClient(uzaiConsoleSysConfig.getJdServerUrl(),"", uzaiConsoleSysConfig.getJdAppKey(), uzaiConsoleSysConfig.getJdAppsecret());
//            UnionOpenPositionCreateRequest request = new UnionOpenPositionCreateRequest();
//            PositionReq positionReq=new PositionReq();
//            positionReq.setUnionId(Long.parseLong(jt.getUnionId()));
//            positionReq.setKey(jt.getAuthKey());
//            positionReq.setUnionType(1);
//            positionReq.setType(4);
//
//            String[] tgNames = createTgName(jdTokenCretePidDto.getPidCount());
//            positionReq.setSpaceNameList(tgNames);
//            request.setPositionReq(positionReq);
//            UnionOpenPositionCreateResponse response=client.execute(request);
//            if (response.getData()==null){
//                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"创建失败，请重试！");
//            }
//            Map<String,String> result = response.getData().getResultList();
//            for (Map.Entry entry:result.entrySet()){
//                pids.add(entry.getValue().toString());
//            }
//
//            jdTokenCreatePidVo = new JdTokenCreatePidVo();
//            jdTokenCreatePidVo.setPids(pids);
//
//        } catch (JdException e) {
//        }
//
//        return jdTokenCreatePidVo;
//
//    }
//
//    //随机创立任意数目的随机码
//    private String[] createTgName(int count){
//        RandomString randomString = new RandomString(6);
//        String TG_PREFIX = "yzsoft_";
//        List<String> list = new ArrayList<>();
//        for (int i=0;i<count;i++){
//            String tgName = TG_PREFIX+randomString.nextString();
//            if (list.contains(tgName)){
//                i=i-1;
//                continue;
//            }
//            list.add(tgName);
//        }
//        String[] arr = new String[list.size()];
//        return list.toArray(arr);
//    }
//
//    public Page<PidVo> queryPid(JdPidQuery jdPidQuery) {
//
//        if(jdPidQuery.getId() == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
//        }
//
//        JdToken jt = jdTokenMapper.selectById(jdPidQuery.getId(), jdPidQuery.getMerId());
//
//        if (jt==null){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.PARAM_ERROR);
//        }
//
//        JdClient client=new DefaultJdClient(uzaiConsoleSysConfig.getJdServerUrl(),"", uzaiConsoleSysConfig.getJdAppKey(), uzaiConsoleSysConfig.getJdAppsecret());
//        UnionOpenPositionQueryRequest request=new UnionOpenPositionQueryRequest();
//        Map<String,Object> result = pidList(client, request, jdPidQuery.getCurrent(), jdPidQuery.getSize(), jt);
//        Page<PidVo> pidVoPage = new Page<>();
//        pidVoPage.setRecords((List<PidVo>) result.get("result"));
//        pidVoPage.setTotal((Integer) result.get("count"));
//        return pidVoPage;
//    }
//
//    //查询京东联盟的推广位列表
//    private Map<String,Object> pidList(JdClient client,UnionOpenPositionQueryRequest request,
//                                       int pageIndex,int pageSize, JdToken jt){
//        Map<String,Object> res = new HashMap<>();
//        try {
//            jd.union.open.position.query.request.PositionReq positionReq=new jd.union.open.position.query.request.PositionReq();
//            positionReq.setUnionId(Long.parseLong(jt.getUnionId()));
//            positionReq.setKey(jt.getAuthKey());
//            positionReq.setUnionType(3);
//            positionReq.setPageIndex(pageIndex);
//            positionReq.setPageSize(pageSize);
//            request.setPositionReq(positionReq);
//            UnionOpenPositionQueryResponse response=client.execute(request);
//            List<PidVo> result = new ArrayList<>();
//            int count = 0;
//            if (response.getData()!=null &&
//                    response.getData().getResult()!=null && response.getData().getResult().length>0){
//                PositionResp[] pr = response.getData().getResult();
//                for (int i=0;i<pr.length;i++){
//                    PidVo pidVo = new PidVo();
//                    pidVo.setId(String.valueOf(pr[i].getId()));
//                    pidVo.setName(pr[i].getSpaceName());
//                    result.add(pidVo);
//                }
//                count = response.getData().getTotal().intValue();
//            }
//            res.put("result",result);
//            res.put("count",count);
//        } catch (JdException e) {
//        }
//        return res;
//    }

    /**
     * 设置PID
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdTokenInfoDto
     * @return null
     */
    public void setPid(JdTokenInfoDto jdTokenInfoDto){
        if(jdTokenInfoDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主键ID不能为空");
        }

        JdToken jdToken = jdTokenMapper.selectById(jdTokenInfoDto.getId(), jdTokenInfoDto.getMerId());

        Integer now = DateUtil.getNowTime();
        jdToken.setUpdateTime(now);
        jdTokenMapper.updateByIdSelective(jdToken);
    }

    @Override
    public List<JdToken> listJdToken(Long merId, List<Long> leagueAccountIds) {
        if (Objects.isNull(merId) || CollectionUtil.isEmpty(leagueAccountIds)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<JdToken> condition = Wrappers.lambdaQuery(JdToken.class);
        condition.eq(JdToken::getMerId, merId).in(JdToken::getId, leagueAccountIds);
        return jdTokenMapper.selectList(condition);
    }
}
